"use strict";

const logger = log.getLogger("sdk");
const common = requireMod("common");
const commonService = requireService("common");

const jobs_path = getSysConfig("jobsPath");

const REPLACE_DATA = {
    "protocol": getSysConfig("protocol")
    ,"collectUrl": getSysConfig("collectUrl")
};

/**
 * 活动 sdk 构成列表
 * @type {Array}
 */
const ACTIVITY_SDK_JOBS = [
    "sdk-conf"
    ,"base"
    ,"collect"
    ,"pageview"
    ,"click"
    ,"event"
    ,"share"
    ,"stay"
    ,"unload"
    ,"user"
    ,"sdk-boot"
];

/**
 * 获取活动 sdk
 * @return {Generator}
 */
function onGetSdk(ctx) {
    ctx.query.task_id = ctx.query.task_id || "";

    var re = "";
    ACTIVITY_SDK_JOBS.forEach(file => {
        var dat = commonService.cache.get(file);
        if (!dat) {
            dat = commonService.read(jobs_path, file + ".js", logger);
            if (dat) {
                commonService.cache.set(file,dat);
            }
        }
        re += "\n" + dat;
    });

    var rData = common.merge(ctx.query, REPLACE_DATA);
    re = common.labelReplace(re, rData);
    re = commonService.warpRespone(
        re
    );
    rData = null;

    commonService.setHeader.call(ctx);

    ctx.body = re;
}


module.exports = {
    "/sdk/activity":["GET", onGetSdk]
}
